var express = require('express');
var http = require('http');
var app = express();
var fortune = require('./lib/fortune.js');
// 设置handlebar视图引擎
var handlebars = require('express3-handlebars').create({ 
    defaultLayout: 'main',
    helpers: {
        /*section: function(name, options){
            if (!this._section) {
                this._section = {};
            }
            this._section[name] = options.fn(this);
            return null;
        }
        */
        static: function(name){
            return require('./lib/static.js').map(name);
        }
    }
});

var formidable = require('formidable');
var jqupload = require('jquery-file-upload-middleware');
var credentials = require('./credentials');
var nodemailer = require('nodemailer');
var vhost = require('vhost');
var getWeatherData = require('./public/getpartials/getWeatherData.js');
var routes = require('./routes.js');
var dataDir = __dirname + '/data';
var vocationPhotoDir = __dirname + '/vocationPhotoDir';
var admin = express.Router();
app.use(vhost('admin.*', admin));
function saveContestEntry(contestName, email, year, month, photoPath) {

}

app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

app.set('port', process.env.PORT || 3200);

app.use(express.static(__dirname + '/public'));

app.use(function(req, res, next){
    res.locals.showTests = app.get('env') !== 'production' && req.query.test === '1';
    next();
});
var static = require('./lib/static.js').map;
app.use(function(req, res, next){
    var now = new Date();
    res.locals.logoImage = static('/img/logo.png');
    next();
});

app.use(require('body-parser')());
app.use(require('cookie-parser')(credentials.cookieSecret));
app.use(require('express-session')());


app.use(function(req, res, next){
    var cluster = require('cluster');
    if (cluster.isWorker) {
        console.log('Worker %d received request', cluster.worker.id);
    }
    next();
});

app.use(function(req, res, next){
    if(!res.locals.partials){
        res.locals.partials = {}
    }
    res.locals.partials.weather = getWeatherData();
    next();
})

admin.get('/', function(req, res){
    res.render('admin/home');
});
admin.get('/users', function(req, res){
    res.render('admin/users');
});

app.get('/newsletter', function(req, res){
    res.cookie('monster', 'Monster first');
    res.cookie('signed_monster', 'Monster signed first', {signed: true});
    req.session.userName = 'Anonymous';
    res.render('newsletter', {
        csrf: 'CSRF token goes here'
    })
})

app.get('/nursery-rhyme', function(req, res){
    res.render('nursery-rhyme')
})

app.get('/data/nursery-rhyme', function(req, res){
    res.json({
        data: {
            animal: 'squirrel',
            bodyPart: 'tail',
            adjective: 'bushy',
            noun: 'heck'
        },
        code: 0
    })
})

app.post('/newsletter', function(req, res){
    var name = req.body.name || '', email = req.body.email || '';
    // 输入验证
    if (!email.match(VALID_EMAIL_REGEX)) {
        if (req.xhr) {
            return res.json({
                error: 'Invalid name email address.'
            })
        }
        req.session.flash = {
            type: 'danger',
            intro: 'Validation error!',
            message: 'The email address you entered was not valid.'
        }
        return res.redirect(303, '/newsletter/archive');
    }
    new NewsletterSignup({name: name, email: email}).save(function(err){
        if(err){
            if(req.xhr) {
                return res.json({
                    error: 'Database Error.'
                })
            }
             req.session.flash = {
                type: 'danger',
                intro: 'Database error!',
                message: 'There was a database error;please try again later'
            }
            return res.redirect(303, '/newsletter/archive');
        }
        if (req.xhr) {
            return res.json({
                success: true
            })
        }
        req.session.falsh = {
            type: 'success',
            intro: 'Thank you',
            message: 'You have now been signed up for the newsletter.'
        };
        return res.redirect(303, '/newsletter/archive');
    })
})

app.get('/contest/vacation-photo', function(req, res){
    var monster = req.cookies.monster;
    var signedMonster = req.signedCookies.signed_monster;
    var now = new Date();
    var userName = req.session.userName
    res.render('contest/vacation-photo', {
        year: now.getFullYear(),
        month: now.getMonth(),
        monster: monster,
        signedMonster: signedMonster,
        userName: userName
    })
})

app.get('/upload', function(req, res, next){
    var now = new Date();
    res.render('contest/upload')
    // jqupload.fileHandler({
    //     uploadDir: function(){
    //         return __dirname + '/public/uploads/' + now;
    //     },
    //     uploadUrl: function(){
    //         return '/uploads/' + now;
    //     }
    // })(req, res, next)
})

app.post('/contest/vacation-photo/:year/:month', function(req, res){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files){
        if (err) {
            return res.redirect(303, '/error');
        }
        if (err) {
            res.session.flash = {
                type: 'danger',
                intro: 'Oops!',
                message: 'There was an error procession your submission.' +
                    'Please try again.'
            };
            return res.redirect(303, '/contest/vacation-photo');
        }
        var photo = files.photo;
        var dir = vacationPhotoDir + '/' + new Date();
        var path = dir + '/' + photo.name;
        fs.mkdirSync(dir);
        fs.renameSync(photo.path, dir + '/' + photo.name);
        saveContestEntry('vacation-photo', fields.email, req.params.year, req.params.month, path);
        req.session.flash = {
            type: 'success',
            intro: 'Good luck',
            message: 'You have been entred into the contest.'
        };
        return res.redirect(303, '/contest/vacation-photo/entries')
    })
})


var name = '';

app.post('/process', function(req, res) {
    if (req.xhr || req.accepts('json,html') === 'json') {
        res.send({success: true})
    } else {
        name = req.body.name;
        // res.render('thank-you')
        res.redirect(303, '/thank-you');
    }
    // name = req.body.name;
    // // res.render('thank-you')
    // res.redirect(303, '/thank-you');
})

app.get('/thank-you', function(req, res){
    res.render('thank-you', {
        name: name
    });
})
routes(app); // 加载home和about
// app.get('/', function(req, res){
//     // res.type('text/plain');
//     // res.send('Meadowlark Travel');
//     res.render('home');
// })
// app.get('/about', function(req, res){
//     // res.type('text/plain');
//     // res.send('About Meadowlark Travel');
//     var randomFortune = fortune.getFortune();
//     res.render('about', {
//         fortune: randomFortune,
//         pageTestScript: '/qa/tests-about.js'
//     });
// })

// app.get('/tours/hood-river', function(req, res){
//     res.render('tours/hood-river');
// })
// app.get('/tours/request-group-rate', function(req, res){
//     res.render('tours/request-group-rate');
// })

// 处理未捕获的异常
app.get('/fail', function(req, res){
    throw new Error('Nope!');
})

app.get('/epic-fail', function(req, res){
    process.nextTick(function(){
        throw new Error('Kaboom!')
    })
})

var autoViews = {};
var fs = require('fs');

// render .handlebars文件
app.use(function(req, res, next){
    var path = req.path.toLowerCase();
    if (autoViews[path]) {
        return res.render(autoViews[path])  
    }

    if (fs.existsSync(__dirname + '/views' + path + '.handlebars')) {
        autoViews[path] = path.replace(/^\//, '');
        return res.render(autoViews[path])
    }
    next();
})

// 定制404页面
app.use(function(req, res){
    // res.type('text/plain');
    res.status(404);
    // res.send('404 - Not Found');
    res.render('404');
});
 
// 定制500页面
app.use(function(err, req, res, next){
    console.error(err.stack);
    // res.type('text/plain');
    res.status(500);
    // res.send('500 - Server Error');
    res.render('500');
})

// app.listen(app.get('port'), function() {
//     console.log('Express started on http://localhost:' + app.get('port') + '; press Ctrl - C to terminate.');
// })

function startServer() {
    http.createServer(app).listen(app.get('port'), function(){
        console.log('Express started in ' + app.get('evn') +
            ' mode on http://localhost:' + app.get('port') +
            '; press Ctrl-C to terminate.')
    })
}

if (require.main == module) {
    // 应用程序直接运行；启动应用服务器
    startServer();
} else {
    module.exports = startServer;
}

